package com.bw.unit3.view.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import com.bw.unit3.R
import com.bw.unit3.base.BaseFragment
import com.bw.unit3.bean.CartBean
import com.bw.unit3.databinding.FragmentCartBinding
import com.bw.unit3.view.adapter.CartAdapter
import com.bw.unit3.viewmodel.CartViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * create an instance of this fragment.
 */
class CartFragment : BaseFragment<CartViewModel, FragmentCartBinding>(R.layout.fragment_cart) {

    lateinit var adapter: CartAdapter
    val mdata = mutableListOf<CartBean>()
    override fun initData() {

        viewModel.liveDataCarts.observe(this) {
            mdata.clear()
            mdata.addAll(it.data)
            adapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        viewModel.getCarts()
        adapter = CartAdapter(activity, R.layout.item_cart_layout, mdata)
        dataBinding.rvCart.layoutManager = LinearLayoutManager(activity)
        dataBinding.rvCart.adapter = adapter

        //处理全选按钮
        dataBinding.checkbox.setOnClickListener {
            mdata.forEach {
                it.isCheck = dataBinding.checkbox.isChecked
            }
            //计算底部金额
            EventBus.getDefault().post("cart")
        }

    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventsMsg(msg: String) {
        var totalPrice = 0
        var flagAll = true
        var num = 0
        mdata.forEach {
            if (it.isCheck) {
                totalPrice += it.goods_default_price
                num++
            } else {
                flagAll = false
            }
        }

        adapter.notifyDataSetChanged()
        dataBinding.checkbox.isChecked = flagAll
        dataBinding.tvCount.text = "结算${num}"
        dataBinding.tvPriceAll.text = "¥${totalPrice}"
    }
}